#!/bin/bash

# GitCode 问题反馈插件本地安装脚本
echo "🚀 开始本地安装 GitCode 问题反馈插件..."

# 检查是否在 GitBook 项目中
if [ ! -f "book.json" ] && [ ! -f "book.js" ]; then
    echo "❌ 错误：请在 GitBook 项目根目录中运行此脚本"
    echo "💡 提示：确保当前目录包含 book.json 或 book.js 文件"
    exit 1
fi

# 检查插件是否已构建
if [ ! -f "../assets/plugin.js" ]; then
    echo "❌ 错误：插件未构建"
    echo "💡 正在构建插件..."
    cd ..
    npm run build
    cd example
fi

# 创建插件目录
PLUGIN_DIR="node_modules/gitbook-plugin-gitcode-issue-feedback"
echo "📁 创建插件目录: $PLUGIN_DIR"
mkdir -p "$PLUGIN_DIR"

# 复制插件文件
echo "📦 复制插件文件..."
cp ../assets/plugin.js "$PLUGIN_DIR/"
cp ../package.json "$PLUGIN_DIR/"

# 创建插件入口文件
echo "📝 创建插件入口文件..."
cat > "$PLUGIN_DIR/index.js" << 'EOF'
module.exports = {
    website: {
        assets: "./",
        js: ["plugin.js"]
    }
};
EOF

# 更新 book.json 或 book.js
echo "⚙️ 更新 GitBook 配置..."

if [ -f "book.json" ]; then
    # 更新 book.json
    if grep -q "gitcode-issue-feedback" book.json; then
        echo "✅ book.json 中已包含插件配置"
    else
        echo "📝 添加插件到 book.json..."
        # 这里需要手动添加，因为 JSON 编辑比较复杂
        echo "请手动在 book.json 的 plugins 数组中添加 \"gitcode-issue-feedback\""
        echo "并在 pluginsConfig 中添加配置："
        echo "  \"gitcode-issue-feedback\": {"
        echo "    \"repo\": \"your-username/your-repo\","
        echo "    \"label\": \"报告问题\","
        echo "    \"private\": false"
        echo "  }"
    fi
elif [ -f "book.js" ]; then
    echo "✅ 检测到 book.js 文件"
    echo "请确保 book.js 中包含插件配置"
fi

echo ""
echo "✅ 本地安装完成！"
echo ""
echo "📋 下一步："
echo "1. 检查 book.json 或 book.js 中的插件配置"
echo "2. 运行 'gitbook serve' 或 'gitbook build'"
echo "3. 在浏览器中测试插件功能"
echo ""
echo "🔧 插件配置示例："
echo "  plugins: [\"gitcode-issue-feedback\"]"
echo "  pluginsConfig: {"
echo "    \"gitcode-issue-feedback\": {"
echo "      \"repo\": \"your-username/your-repo\","
echo "      \"label\": \"报告问题\","
echo "      \"private\": false"
echo "    }"
echo "  }"